package com.android.wordbook;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AddActivity extends AppCompatActivity {
    DBHelper helper = null;
    private Activity activity;
    private EditText etWord;//单词
    private EditText etNote;//注释
    private Button btnSave;//保存
    private WordItem mWordItem;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity=this;
        setContentView(R.layout.activity_add);
        helper = new DBHelper(this);
        etWord=findViewById(R.id.et_word);
        etNote=findViewById(R.id.et_note);
        btnSave=findViewById(R.id.btn_save);
        mWordItem = (WordItem) getIntent().getSerializableExtra("word");
        if (mWordItem != null) {
            etWord.setText(mWordItem.getWord());
            etNote.setText(mWordItem.getNote());
        }
        setViewListener();
    }

    
    private void setViewListener() {
        //保存
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = helper.getWritableDatabase();
                String word=etWord.getText().toString();
                String note=etNote.getText().toString();
                if ("".equals(word)) {
                    Toast.makeText(activity,"单词不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(note)) {
                    Toast.makeText(activity,"注释不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mWordItem == null) {//新增
                    String sql = "insert into word(word,note) values(?,?)";
                    db.execSQL(sql,new Object[]{word,note});
                    Toast.makeText(AddActivity.this,"新增成功",Toast.LENGTH_SHORT).show();
                }else {//修改
                    db.execSQL("update word set word = ?, note = ?where id=?", new Object[]{word,note, mWordItem.getId()});
                    Toast.makeText(AddActivity.this,"更新成功",Toast.LENGTH_SHORT).show();
                }
                db.close();
                Toast.makeText(activity,"保存成功", Toast.LENGTH_LONG).show();
                finish();
            }
        });
    }
}
